package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class SubjectExcelDataListener extends AnalysisEventListener<SubjectExcelData> {
    @Autowired
    SubjectMapper subjectMapper ;

    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
        //保存二级分类必须得先有一级分类
        String levelOneSubjectTitle = subjectExcelData.getLevelOneSubjectTitle();
        String levelTwoSubjectTitle = subjectExcelData.getLevelTwoSubjectTitle();
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>() ;
        queryWrapper.eq(Subject::getTitle,levelOneSubjectTitle) ;
        queryWrapper.eq(Subject::getParentId,"0") ;
        Subject pSubject = subjectMapper.selectOne(queryWrapper);
        if (pSubject == null) {
            //新增一级分类
            pSubject = new Subject() ;
            pSubject.setSort(0) ;
            pSubject.setParentId("0") ;
            pSubject.setTitle(levelOneSubjectTitle) ;
            subjectMapper.insert(pSubject) ;
        }
        queryWrapper.clear();
        queryWrapper.eq(Subject::getTitle,levelTwoSubjectTitle) ;
        queryWrapper.eq(Subject::getParentId,pSubject.getId()) ;
        Integer result = subjectMapper.selectCount(queryWrapper);
        if (result == 0) {
            //新增二级标题
            Subject cSubject = new Subject() ;
            cSubject.setTitle(levelTwoSubjectTitle) ;
            cSubject.setSort(0) ;
            cSubject.setParentId(pSubject.getId()) ;
            subjectMapper.insert(cSubject) ;

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
